package com.gy.service.impl;

import com.aaa.entity.CareOrderItem;
import com.aaa.entity.OrderCharge;
import com.aaa.entity.OrderChargeItem;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPayUtil;
import com.gy.mapper.CareOrderItemMapper;
import com.gy.mapper.OrderChargeItemMapper;
import com.gy.mapper.OrderChargeMapper;
import com.gy.service.OrderChargeService;
import com.gy.util.HttpClient;
import com.gy.vo.ChargeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author GaoYa
 * @Date 2023/3/24 11:04
 * @Version 1.5
 */
@Service
public class OrderChargeServiceImpl implements OrderChargeService {
    @Autowired(required = false)
    private OrderChargeMapper orderChargeDao;

    @Autowired(required = false)
    private OrderChargeItemMapper orderChargeItemDao;

    @Autowired(required = false)
    private CareOrderItemMapper careOrderItemDao;


    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;
    /**
     * 分页查询以及模糊查询
     *
     * @param current
     * @param size
     * @param chargeVo
     * @return
     */
    @Override
    public Result<IPage<OrderCharge>> findAll(Integer current, Integer size, ChargeVo chargeVo) {
        IPage<OrderCharge> page = new Page<>(current, size);
        QueryWrapper<OrderCharge> queryWrap = new QueryWrapper();
        if (StringUtils.hasText(chargeVo.getPatientName())) {
            queryWrap.eq("patient_name", chargeVo.getPatientName());
        }
        if (StringUtils.hasText(chargeVo.getRegId())) {
            queryWrap.eq("reg_id", chargeVo.getRegId());
        }
        IPage<OrderCharge> page1 = orderChargeDao.selectPage(page, queryWrap);
        return new Result<IPage<OrderCharge>>(2000, "查询成功", page1);
    }

    /**
     * 查看详情
     *
     * @param orderId
     * @return
     */
    @Override
    public Result<List<OrderChargeItem>> findAllUserId(String orderId) {
        List<OrderChargeItem> allUserId = orderChargeDao.findAllUserId(orderId);
        return new Result<List<OrderChargeItem>>(2000, "查询成功", allUserId);
    }


    @Override
    public Result<Integer> CashCharges(String orderId) {
        Integer integer = orderChargeDao.CashCharges(orderId);
        QueryWrapper<OrderChargeItem> queryWrap = new QueryWrapper();
        queryWrap.eq("order_id", orderId);
        List<OrderChargeItem> orderChargeItems = orderChargeItemDao.selectList(queryWrap);
        for (OrderChargeItem orderItem : orderChargeItems) {
            String itemId = orderItem.getItemId();
            QueryWrapper<CareOrderItem> queryParams = new QueryWrapper<>();
            queryParams.eq("item_id", itemId);
            careOrderItemDao.updateStatus(itemId);
        }
        return new Result<Integer>(2000, "修改成功", integer);
    }

    /**
     * 收费列表微信收费
     * @param orderId
     * @return
     */
    @Override
    public Result payForItem(String orderId) {
        // 根据前来传过来的参数获取患者名称
        QueryWrapper<OrderCharge> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id",orderId);
        OrderCharge orderCharge = orderChargeDao.selectOne(queryWrapper);
        String patientName = orderCharge.getPatientName();
        //获取总金额
        BigDecimal orderAmount = orderCharge.getOrderAmount();
        try {
            // 设置请求的参数
            HashMap<String, String> map = new HashMap<>();
            map.put("appid",appId);
            map.put("mch_id",mchId);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body",patientName);
            map.put("out_trade_no",orderId);
            //支付金额设置成0.01，毕竟钱不是大风刮来的
            map.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
            map.put("spbill_create_ip","127.0.0.1");
            map.put("notify_url","http:localhost:8080/charge/docharge");
            map.put("trade_type", "NATIVE");
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map,apiKey));
            httpClient.post();
            // 获取请求的响应结果
            String content = httpClient.getContent();
            //装换为map格式
            Map<String, String> stringMap = WXPayUtil.xmlToMap(content);
            if (stringMap.get("result_code").equals("SUCCESS")) {
                Map<String, Object> result = new HashMap<>();
                result.put("codeUrl", stringMap.get("code_url"));
                result.put("price", orderAmount);
                result.put("orderId", orderId);
                return new Result(2000,"生成二维码成功",result);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(2000,"订单失效了",null);
    }
}
